<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card shadow="never" class="operation-card">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>新增用户
      </el-button>
      <el-button :disabled="!selectedIds.length" @click="handleBatchDelete">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
      <el-button @click="refreshTable">
        <el-icon><Refresh /></el-icon>刷新
      </el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 用户表单对话框 -->
    <UserFormDialog
      v-model="dialog.visible"
      :form-data="dialog.formData"
      :mode="dialog.mode"
      @success="refreshTable"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import UserFormDialog from '@/components/ui/UserFormDialog.vue'
import type { UserItem } from '@/api/types/user'

const userStore = useUserStore()

// 搜索表单
const searchForm = reactive({
  username: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const userList = ref<UserItem[]>([])
const selectedIds = ref<string[]>([])

// 对话框控制
const dialog = reactive({
  visible: false,
  mode: 'create' as 'create' | 'edit',
  formData: {} as Partial<UserItem>
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true
    // const params = {
    //   ...searchForm,
    //   page: pagination.current,
    //   size: pagination.size
    // }
    // const res = await userStore.getUserList(params)
    // userList.value = res.list
    // pagination.total = res.total
  } finally {
    loading.value = false
  }
}

// 搜索相关方法
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.status = ''
  handleSearch()
}

// 表格相关方法
const handleSelectionChange = (selection: UserItem[]) => {
  selectedIds.value = selection.map(item => item.id)
}

const refreshTable = () => {
  fetchUserList()
}

// 分页方法
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchUserList()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchUserList()
}

// 操作相关方法
const handleCreate = () => {
  dialog.mode = 'create'
  dialog.formData = {}
  dialog.visible = true
}

const handleEdit = (row: UserItem) => {
  dialog.mode = 'edit'
  dialog.formData = { ...row }
  dialog.visible = true
}

const handleDelete = async (row: UserItem) => {
  try {
    await ElMessageBox.confirm(`确定删除用户 ${row.username} 吗？`, '提示', {
      type: 'warning'
    })
    await userStore.deleteUser(row.id)
    ElMessage.success('删除成功')
    refreshTable()
  } catch {
    // 用户取消
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selectedIds.value.length} 个用户吗？`, '提示', {
      type: 'warning'
    })
    await userStore.batchDeleteUsers(selectedIds.value)
    ElMessage.success('删除成功')
    refreshTable()
  } catch {
    // 用户取消
  }
}

// 初始化加载
onMounted(() => {
  fetchUserList()
})
</script>

<style lang="scss" scoped>
.user-management {
  .search-card {
    margin-bottom: 20px;
    
    :deep(.el-form-item) {
      margin-bottom: 0;
    }
  }
  
  .operation-card {
    margin-bottom: 20px;
  }
}
</style>